﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Application.App;
using FacadeApi.Extension;
using Infrastructure.Error;
using MassTransit;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using OtherLib.AliPay;
using OtherLib.Getui;
using OtherLib.TenXun;
using Utility;
using Infrastructure.MessageBus;
using Domain.Services;
using Domain.IRepositorys;
using Microsoft.Extensions.Configuration;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using DTO;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System.Net.Http;
using System.Net;

namespace FacadeApi.Controllers
{
#if DEBUG
    [Route("api/[controller]/[action]")]
    [ApiController]
#endif
    public class TestController : ControllerBase
    {
        public TestApplication testApplication { get; set; }
        public IUserRepository userRepository { get; set; }
        public IHttpClientFactory httpClientFactory { get; set; }
        public IMService iMService { get; set; }
        [HttpPut]
        public ActionResult Test01([FromServices]IBus bus)
        {
            //bus.Publish<Domain.Event.UserLoginEvent>(new Domain.Event.UserLoginEvent()).GetAwaiter().GetResult();
            //testApplication.Test01();
            //return this.Success(AliPayUtil.AliPlay("1", "123854615244615", "测试","1"));

            //创建openfire账号
            //var authorization = "XSjq9C70bRcyFjmn";

            //var xml = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?><user><username>test3</username><password>12346</password><name>Test User</name></user>";

            //var ret = HttpUtil.PostXml("http://im.jhgoulaifu.com:9090/plugins/restapi/v1/users", xml, authorization).GetAwaiter().GetResult();

            var u = userRepository.GetByKey(2);
            //iMService.CreateIMUser(u);
            u.NickName = "bbb";
            u.Pwd = "ggs";
            var ret = iMService.UpdateIMUser(u);
            return this.Success(ret);
        }

        [HttpPut]
        public ActionResult Test02(string gmtTime, string urlmd5)
        {
            //var v1 = MyHmacUtil.CreateToken($"x-date: {gmtTime}\ncontent-md5: {urlmd5}", "5tgb6yhf");
            //var r = FaceIDUtil.MakeSign("", 1);
            //var r= FaceIDUtil.GetTicket("1");
            //return this.Success(r);
            //var r = TLSSigAPIv2.GetInstance().genUserSig("a15658610023");
            //return this.Success(r);
            var http = httpClientFactory.CreateClient();

            http.DefaultRequestVersion = HttpVersion.Version20;

            return this.Success(http.GetAsync("https://baidu.com").GetAwaiter().GetResult());
        }

        public IConfiguration configuration { get; set; }

        [HttpPut]
        public ActionResult Test03()
        {
            //testApplication.Test02();
            var connectionStr = configuration.GetValue<string>("RabbitMQ.ConnectionStr");
            var connectionArr = connectionStr.Split(",");

            var strArr = connectionArr[0].Split(";");

            var hostStr = strArr[0].Split("=")[1];
            var virtualHostStr = strArr[1].Split("=")[1];
            var usernameStr = strArr[2].Split("=")[1];
            var passwordStr = strArr[3].Split("=")[1];

            var factory = new ConnectionFactory() { HostName = hostStr, VirtualHost = virtualHostStr, UserName = usernameStr, Password = passwordStr };
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {

                channel.QueueDeclare(queue: "openfiremsg",
                                     durable: true,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);
                channel.QueueDeclare(queue: "openfiremsg_miss",
                                     durable: true,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);
                //channel.ExchangeDeclare("openfiremsg_miss", ExchangeType.Direct, true, false);
                //channel.QueueBind("openfiremsg_miss", "", "openfiremsg_miss");

                var properties = channel.CreateBasicProperties();
                //队列持久化
                properties.Persistent = true;

                channel.BasicPublish("", "openfiremsg_miss", properties, System.Text.Encoding.UTF8.GetBytes("hello"));
            }


            return this.Success(null);
        }

        [HttpPut]
        public ActionResult Test04()
        {
            Dictionary<string, object> map = new Dictionary<string, object>();

            map.Add("cc", "bb");



            //GetuiUtil.SendMsgNotifyApp("abc", "cba", map);
            GetuiUtil.SendMsgTransmissionApp(map);


            return this.Success(null);
        }

        [HttpPost]
        public ActionResult Test05()
        {
            var formFile = Request.Form.Files[0];
            byte[] bytes;
            using (MemoryStream memoryStream = new MemoryStream())
            {
                formFile.CopyTo(memoryStream);
                bytes = memoryStream.ToArray();
            }

            var path = CosUtil.UploadObject($"test/{Guid.NewGuid().ToString("N")}{Path.GetExtension(formFile.FileName)}", bytes);

            return this.Success(path);
        }

        [HttpGet]
        public ActionResult Test06()
        {
            //var r = IDVaildUtil.ValidCard("330326198702032916", "杨周");
            var u = userRepository.GetByKey(33);

            var s = iMService.GetIMUserPwd(u);


            return this.Success(s);
        }

        [HttpGet]
        public ActionResult Test07()
        {
            var serialNo = IDGeneratorUtil.GetId();
            var util = TenXunPayUtil.GetUtilByName("App");
            var r = util.AppPay("abcc", serialNo.ToString(), 100).GetAwaiter().GetResult();
            //var r=AliPayUtil.AliPlay("1", serialNo.ToString(), "充值", "1");
            return this.Success(r);
        }

        [HttpGet]
        public ActionResult Test08()
        {
            var deviceID = (string)Request.Headers["DeviceID"];

            if (string.IsNullOrWhiteSpace(deviceID))
            {
                return this.FailResult(null, "参数错误,未找到DeviceID!");
            }

            try
            {
                var t = TimeSpan.FromMinutes(3);

                var Token = TokenManager.GetDeviceToken(deviceID, t);

 
                return this.Success(new { Token = Token, Expire = DateTime.Now.AddSeconds(t.TotalSeconds) });
            }
            catch (BizException ex)
            {
                return this.FailResult(ex.data, ex.Message);
            }
            catch (Exception ex)
            {
                return this.FailResult(null, "系统繁忙，请稍后重试!");
            }
        }

        public UserApplication userApplication { get; set; }
        [HttpGet]
        public ActionResult Test09()
        {
            //var deviceID = (string)Request.Headers["DeviceID"];

            //if (string.IsNullOrWhiteSpace(deviceID))
            //{
            //    return this.FailResult(null, "参数错误,未找到DeviceID!");
            //}

            try
            {
                var r = userApplication.Login(new DTO.UserLoginInput() { 
                    Infomation="test",
                    IP="::0",
                    Phone= "15727903515",
                    PhoneCode="112244",
                    Platfrom="IOS"
                });


                return this.Success(r);
            }
            catch (BizException ex)
            {
                return this.FailResult(ex.data, ex.Message);
            }
            catch (Exception ex)
            {
                return this.FailResult(null, "系统繁忙，请稍后重试!");
            }
        }
        public WxMiniApplication wxMiniApplication { get; set; }

        [AllowAnonymous, HttpPost]
        public ActionResult<UserLoginOutput> Text10()//WxCodeInfoInput wxCodeInfoInput
        {
            string ipaddress = this.HttpContext.Connection.RemoteIpAddress.ToString();
            try
            {
                //var json = WxMiniUtil.GetOpendidAndSessionkey(wxCodeInfoInput.wxCode);
                //if (json.ContainsKey("errcode"))
                //{
                //    string errcode = Convert.ToString(json.Property("errcode").Value);
                //    return this.FailResult(errcode);
                //}
                //var openId = Convert.ToString(json.Property("openid").Value);
                var openId = "oTooA5EJXawGe2-g-0YSaTqgWVFc";

                var loginInfo = wxMiniApplication.TryWxMiniLoginByOpenId(openId, ipaddress);

                if (loginInfo != null) return this.Success(loginInfo);

                return this.FailResult(null);
                //var session_key = Convert.ToString(json.Property("session_key").Value);
                //var unionId = string.Empty;
                //var phone = string.Empty;
                //var headimg = string.Empty;
                //var nickname = string.Empty;
                //if (json.ContainsKey("UnionId")) unionId = Convert.ToString(json.Property("UnionId").Value);
                //else
                //{
                //    string decryptedContent = EncryptorUtil.AESDecrypt(wxCodeInfoInput.encryptedData, wxCodeInfoInput.iv, session_key);
                //    JObject jsonObject = (JObject)JsonConvert.DeserializeObject(decryptedContent);

                //    //Console.WriteLine(decryptedContent);
                //    unionId = Convert.ToString(jsonObject.Property("unionId").Value);
                //    if (jsonObject.ContainsKey("purePhoneNumber")) phone = jsonObject.Value<string>("purePhoneNumber");
                //    if (jsonObject.ContainsKey("avatarUrl")) headimg = Convert.ToString(jsonObject.Property("avatarUrl").Value);
                //    if (jsonObject.ContainsKey("nickName")) nickname = Convert.ToString(jsonObject.Property("nickName").Value);

                //}

                //var obj = new { openId, unionId, phone, headimg, session_key, nickname };



                //return this.Success(EncryptorUtil.Encrypt(JsonConvert.SerializeObject(obj), "jbelmaxidvlrecnb", "5992038507950310"));
            }
            catch (BizException ex)
            {
                return this.FailResult(ex.data, ex.Message);
            }
            catch (Exception ex)
            {
                //_logger.LogException(ex);
                return this.FailResult(null, "系统繁忙，请稍后重试!");
            }
        }

    }
}
